package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义 全局异常处理器
 *
 * @author jiang zhongxun
 * @create 2023-03-11 10:44
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理
     *
     * @param e e
     * @return {@link RestErrorResponse}
     */
    @ResponseBody
    @ExceptionHandler(XueChengPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse customException(XueChengPlusException e) {
        /* 记录异常 */
        log.error("系统异常{}", e.getErrMessage(), e);
        /* 解析出异常信息 */
        String errMessage = e.getErrMessage();
        return new RestErrorResponse(errMessage);
    }

    /**
     * 非自定义异常处理
     *
     * @param e e
     * @return {@link RestErrorResponse}
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e) {
        /* 记录异常 */
        log.error("系统异常{}", e.getMessage(), e);
        /* 解析出异常信息 */
        return new RestErrorResponse(CommonError.UNKNOWN_ERROR.getErrMessage());
    }

    /**
     * 方法参数无效异常处理 -- 结合JSR303校验
     *
     * @param e e
     * @return {@link RestErrorResponse}
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        /* 存储错误信息 */
        List<String> errorList = new ArrayList<>();
        bindingResult.getFieldErrors().forEach(item -> errorList.add(item.getDefaultMessage()));
        /* 将 List 中的错误信息拼接起来 */
        String errMessage = StringUtils.join(errorList, ",");
        /* 记录异常 */
        log.error("JSR303校验异常{}", errMessage);
        /* 解析出异常信息 */
        return new RestErrorResponse(errMessage);
    }

}
